package com.xm.redis.redisson;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class OrderService2 {

    @Autowired
    private RedissonClient redissonClient;

    public void createOrder(String orderId) {
        String lockKey = "order:lock:" + orderId;
        RLock lock = redissonClient.getLock(lockKey);

        try {
            // 尝试加锁（最多等待10秒，锁超时自动释放时间30秒）
            boolean isLocked = lock.tryLock(10, 30, TimeUnit.SECONDS);
            if (!isLocked) {
                throw new RuntimeException("系统繁忙，请稍后再试！");
            }

            log.info("已获取锁。");
            processOrder(orderId);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new RuntimeException(e);
        } finally {
            if (lock.isLocked() && lock.isHeldByCurrentThread()) {
                lock.unlock();
                log.info("锁已释放。");
            }
        }
    }

    public void processOrder(String orderId) throws InterruptedException {
        // 订单处理逻辑
        log.info("订单处理中..");

        Thread.sleep(2000);

        log.info("订单处理完成。");
    }
}
